package dbops

import (
	"GoStreamVideoWebsite/api/defs"
	"GoStreamVideoWebsite/api/utils"
	"errors"
	"log"
	"time"
)

func AddUserCredential(username string, pwd string) error {
	lock.Lock()
	defer lock.Unlock()
	//插入用户 和密码
	if err := dbConn.Create(&defs.Users{Username: username, Password: pwd}).Error; err != nil {
		return err
	}
	return nil
}
func GetUserCredential(username string) (string, error) {
	lock.RLock()
	defer lock.RUnlock()
	var user defs.Users
	dbConn.Where("username=?", username).First(&user)
	if user.ID == 0 {
		log.Printf("%s", "Get User Failed")
		return "", errors.New("Get User Failed")
	}
	return user.Password, nil
}
func DeleteUser(username string, pwd string) error {
	lock.Lock()
	defer lock.Unlock()
	var user defs.Users
	if dbConn.Where("username=? and password=?", username, pwd).First(&user).RecordNotFound() {
		return errors.New("User not exists")
	}
	if err := dbConn.Delete(&user).Error; err != nil {
		return errors.New("Delete User failed")
	}
	return nil
}

func AddNewVideo(aid uint, videoname string) (*defs.Video_Info, error) {
	lock.Lock()
	defer lock.Unlock()
	vid := utils.NewUUID()
	t := time.Now()
	ctime := t.Format("Jan 02 2006, 15:04:05")
	video := defs.Video_Info{
		ID:           vid,
		AuthorID:     aid,
		Name:         videoname,
		DisplayCtime: ctime,
	}
	if err := dbConn.Create(&video).Error; err != nil {
		return nil, err
	}
	return &video, nil
}
func GetVideoInfo(vid string) (*defs.Video_Info, error) {
	lock.RLock()
	defer lock.RUnlock()
	var video defs.Video_Info
	if dbConn.Where("id=?", vid).First(&video).RecordNotFound() {
		return nil, errors.New("video not found ")
	}
	return &video, nil
}
func DeleteVideoInfo(vid string) error {
	lock.Lock()
	defer lock.Unlock()
	var video defs.Video_Info
	if dbConn.Where("id=?", vid).First(&video).RecordNotFound() {
		return errors.New("delete failed --not found ")
	}
	if err := dbConn.Delete(&video).Error; err != nil {
		return err
	}
	return nil
}
func AddNewComment(vid string, aid uint, content string) error {
	lock.Lock()
	defer lock.Unlock()
	cid := utils.NewUUID()
	var comment defs.Comments = defs.Comments{
		ID:       cid,
		VideoID:  vid,
		AuthorID: aid,
		Content:  content,
	}
	if err := dbConn.Create(&comment).Error; err != nil {
		return err
	}
	return nil
}
func ListComments(vid string, from, to int64) ([]*defs.CommentWithName, error) {
	lock.RLock()
	defer lock.RUnlock()
	var res []*defs.CommentWithName
	dbConn.Debug().Raw("select comments.id,users.username,comments.content FROM comments "+
		"INNER JOIN users on comments.author_id=users.id where comments.video_id=? AND comments.created_at > FROM_UNIXTIME(?) AND "+
		"comments.created_at <= FROM_UNIXTIME(?)", vid, from, to).Scan(&res)
	return res, nil

}
